home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / subprocess.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-29  |  33KB  |  1,256 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''subprocess - Subprocesses with accessible I/O streams
  5.  
  6. This module allows you to spawn processes, connect to their
  7. input/output/error pipes, and obtain their return codes.  This module
  8. intends to replace several other, older modules and functions, like:
  9.  
  10. os.system
  11. os.spawn*
  12. os.popen*
  13. popen2.*
  14. commands.*
  15.  
  16. Information about how the subprocess module can be used to replace these
  17. modules and functions can be found below.
  18.  
  19.  
  20.  
  21. Using the subprocess module
  22. ===========================
  23. This module defines one class called Popen:
  24.  
  25. class Popen(args, bufsize=0, executable=None,
  26.             stdin=None, stdout=None, stderr=None,
  27.             preexec_fn=None, close_fds=False, shell=False,
  28.             cwd=None, env=None, universal_newlines=False,
  29.             startupinfo=None, creationflags=0):
  30.  
  31.  
  32. Arguments are:
  33.  
  34. args should be a string, or a sequence of program arguments.  The
  35. program to execute is normally the first item in the args sequence or
  36. string, but can be explicitly set by using the executable argument.
  37.  
  38. On UNIX, with shell=False (default): In this case, the Popen class
  39. uses os.execvp() to execute the child program.  args should normally
  40. be a sequence.  A string will be treated as a sequence with the string
  41. as the only item (the program to execute).
  42.  
  43. On UNIX, with shell=True: If args is a string, it specifies the
  44. command string to execute through the shell.  If args is a sequence,
  45. the first item specifies the command string, and any additional items
  46. will be treated as additional shell arguments.
  47.  
  48. On Windows: the Popen class uses CreateProcess() to execute the child
  49. program, which operates on strings.  If args is a sequence, it will be
  50. converted to a string using the list2cmdline method.  Please note that
  51. not all MS Windows applications interpret the command line the same
  52. way: The list2cmdline is designed for applications using the same
  53. rules as the MS C runtime.
  54.  
  55. bufsize, if given, has the same meaning as the corresponding argument
  56. to the built-in open() function: 0 means unbuffered, 1 means line
  57. buffered, any other positive value means use a buffer of
  58. (approximately) that size.  A negative bufsize means to use the system
  59. default, which usually means fully buffered.  The default value for
  60. bufsize is 0 (unbuffered).
  61.  
  62. stdin, stdout and stderr specify the executed programs\' standard
  63. input, standard output and standard error file handles, respectively.
  64. Valid values are PIPE, an existing file descriptor (a positive
  65. integer), an existing file object, and None.  PIPE indicates that a
  66. new pipe to the child should be created.  With None, no redirection
  67. will occur; the child\'s file handles will be inherited from the
  68. parent.  Additionally, stderr can be STDOUT, which indicates that the
  69. stderr data from the applications should be captured into the same
  70. file handle as for stdout.
  71.  
  72. If preexec_fn is set to a callable object, this object will be called
  73. in the child process just before the child is executed.
  74.  
  75. If close_fds is true, all file descriptors except 0, 1 and 2 will be
  76. closed before the child process is executed.
  77.  
  78. if shell is true, the specified command will be executed through the
  79. shell.
  80.  
  81. If cwd is not None, the current directory will be changed to cwd
  82. before the child is executed.
  83.  
  84. If env is not None, it defines the environment variables for the new
  85. process.
  86.  
  87. If universal_newlines is true, the file objects stdout and stderr are
  88. opened as a text files, but lines may be terminated by any of \'\\n\',
  89. the Unix end-of-line convention, \'\\r\', the Macintosh convention or
  90. \'\\r\\n\', the Windows convention.  All of these external representations
  91. are seen as \'\\n\' by the Python program.  Note: This feature is only
  92. available if Python is built with universal newline support (the
  93. default).  Also, the newlines attribute of the file objects stdout,
  94. stdin and stderr are not updated by the communicate() method.
  95.  
  96. The startupinfo and creationflags, if given, will be passed to the
  97. underlying CreateProcess() function.  They can specify things such as
  98. appearance of the main window and priority for the new process.
  99. (Windows only)
  100.  
  101.  
  102. This module also defines two shortcut functions:
  103.  
  104. call(*popenargs, **kwargs):
  105.     Run command with arguments.  Wait for command to complete, then
  106.     return the returncode attribute.
  107.  
  108.     The arguments are the same as for the Popen constructor.  Example:
  109.  
  110.     retcode = call(["ls", "-l"])
  111.  
  112. check_call(*popenargs, **kwargs):
  113.     Run command with arguments.  Wait for command to complete.  If the
  114.     exit code was zero then return, otherwise raise
  115.     CalledProcessError.  The CalledProcessError object will have the
  116.     return code in the returncode attribute.
  117.  
  118.     The arguments are the same as for the Popen constructor.  Example:
  119.  
  120.     check_call(["ls", "-l"])
  121.  
  122. Exceptions
  123. ----------
  124. Exceptions raised in the child process, before the new program has
  125. started to execute, will be re-raised in the parent.  Additionally,
  126. the exception object will have one extra attribute called
  127. \'child_traceback\', which is a string containing traceback information
  128. from the childs point of view.
  129.  
  130. The most common exception raised is OSError.  This occurs, for
  131. example, when trying to execute a non-existent file.  Applications
  132. should prepare for OSErrors.
  133.  
  134. A ValueError will be raised if Popen is called with invalid arguments.
  135.  
  136. check_call() will raise CalledProcessError, if the called process
  137. returns a non-zero return code.
  138.  
  139.  
  140. Security
  141. --------
  142. Unlike some other popen functions, this implementation will never call
  143. /bin/sh implicitly.  This means that all characters, including shell
  144. metacharacters, can safely be passed to child processes.
  145.  
  146.  
  147. Popen objects
  148. =============
  149. Instances of the Popen class have the following methods:
  150.  
  151. poll()
  152.     Check if child process has terminated.  Returns returncode
  153.     attribute.
  154.  
  155. wait()
  156.     Wait for child process to terminate.  Returns returncode attribute.
  157.  
  158. communicate(input=None)
  159.     Interact with process: Send data to stdin.  Read data from stdout
  160.     and stderr, until end-of-file is reached.  Wait for process to
  161.     terminate.  The optional input argument should be a string to be
  162.     sent to the child process, or None, if no data should be sent to
  163.     the child.
  164.  
  165.     communicate() returns a tuple (stdout, stderr).
  166.  
  167.     Note: The data read is buffered in memory, so do not use this
  168.     method if the data size is large or unlimited.
  169.  
  170. The following attributes are also available:
  171.  
  172. stdin
  173.     If the stdin argument is PIPE, this attribute is a file object
  174.     that provides input to the child process.  Otherwise, it is None.
  175.  
  176. stdout
  177.     If the stdout argument is PIPE, this attribute is a file object
  178.     that provides output from the child process.  Otherwise, it is
  179.     None.
  180.  
  181. stderr
  182.     If the stderr argument is PIPE, this attribute is file object that
  183.     provides error output from the child process.  Otherwise, it is
  184.     None.
  185.  
  186. pid
  187.     The process ID of the child process.
  188.  
  189. returncode
  190.     The child return code.  A None value indicates that the process
  191.     hasn\'t terminated yet.  A negative value -N indicates that the
  192.     child was terminated by signal N (UNIX only).
  193.  
  194.  
  195. Replacing older functions with the subprocess module
  196. ====================================================
  197. In this section, "a ==> b" means that b can be used as a replacement
  198. for a.
  199.  
  200. Note: All functions in this section fail (more or less) silently if
  201. the executed program cannot be found; this module raises an OSError
  202. exception.
  203.  
  204. In the following examples, we assume that the subprocess module is
  205. imported with "from subprocess import *".
  206.  
  207.  
  208. Replacing /bin/sh shell backquote
  209. ---------------------------------
  210. output=`mycmd myarg`
  211. ==>
  212. output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
  213.  
  214.  
  215. Replacing shell pipe line
  216. -------------------------
  217. output=`dmesg | grep hda`
  218. ==>
  219. p1 = Popen(["dmesg"], stdout=PIPE)
  220. p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
  221. output = p2.communicate()[0]
  222.  
  223.  
  224. Replacing os.system()
  225. ---------------------
  226. sts = os.system("mycmd" + " myarg")
  227. ==>
  228. p = Popen("mycmd" + " myarg", shell=True)
  229. pid, sts = os.waitpid(p.pid, 0)
  230.  
  231. Note:
  232.  
  233. * Calling the program through the shell is usually not required.
  234.  
  235. * It\'s easier to look at the returncode attribute than the
  236.   exitstatus.
  237.  
  238. A more real-world example would look like this:
  239.  
  240. try:
  241.     retcode = call("mycmd" + " myarg", shell=True)
  242.     if retcode < 0:
  243.         print >>sys.stderr, "Child was terminated by signal", -retcode
  244.     else:
  245.         print >>sys.stderr, "Child returned", retcode
  246. except OSError, e:
  247.     print >>sys.stderr, "Execution failed:", e
  248.  
  249.  
  250. Replacing os.spawn*
  251. -------------------
  252. P_NOWAIT example:
  253.  
  254. pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
  255. ==>
  256. pid = Popen(["/bin/mycmd", "myarg"]).pid
  257.  
  258.  
  259. P_WAIT example:
  260.  
  261. retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
  262. ==>
  263. retcode = call(["/bin/mycmd", "myarg"])
  264.  
  265.  
  266. Vector example:
  267.  
  268. os.spawnvp(os.P_NOWAIT, path, args)
  269. ==>
  270. Popen([path] + args[1:])
  271.  
  272.  
  273. Environment example:
  274.  
  275. os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
  276. ==>
  277. Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
  278.  
  279.  
  280. Replacing os.popen*
  281. -------------------
  282. pipe = os.popen(cmd, mode=\'r\', bufsize)
  283. ==>
  284. pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
  285.  
  286. pipe = os.popen(cmd, mode=\'w\', bufsize)
  287. ==>
  288. pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
  289.  
  290.  
  291. (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
  292. ==>
  293. p = Popen(cmd, shell=True, bufsize=bufsize,
  294.           stdin=PIPE, stdout=PIPE, close_fds=True)
  295. (child_stdin, child_stdout) = (p.stdin, p.stdout)
  296.  
  297.  
  298. (child_stdin,
  299.  child_stdout,
  300.  child_stderr) = os.popen3(cmd, mode, bufsize)
  301. ==>
  302. p = Popen(cmd, shell=True, bufsize=bufsize,
  303.           stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
  304. (child_stdin,
  305.  child_stdout,
  306.  child_stderr) = (p.stdin, p.stdout, p.stderr)
  307.  
  308.  
  309. (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
  310. ==>
  311. p = Popen(cmd, shell=True, bufsize=bufsize,
  312.           stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
  313. (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
  314.  
  315.  
  316. Replacing popen2.*
  317. ------------------
  318. Note: If the cmd argument to popen2 functions is a string, the command
  319. is executed through /bin/sh.  If it is a list, the command is directly
  320. executed.
  321.  
  322. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
  323. ==>
  324. p = Popen(["somestring"], shell=True, bufsize=bufsize
  325.           stdin=PIPE, stdout=PIPE, close_fds=True)
  326. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  327.  
  328.  
  329. (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
  330. ==>
  331. p = Popen(["mycmd", "myarg"], bufsize=bufsize,
  332.           stdin=PIPE, stdout=PIPE, close_fds=True)
  333. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  334.  
  335. The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
  336. except that:
  337.  
  338. * subprocess.Popen raises an exception if the execution fails
  339. * the capturestderr argument is replaced with the stderr argument.
  340. * stdin=PIPE and stdout=PIPE must be specified.
  341. * popen2 closes all filedescriptors by default, but you have to specify
  342.   close_fds=True with subprocess.Popen.
  343.  
  344.  
  345. '''
  346. import sys
  347. mswindows = sys.platform == 'win32'
  348. import os
  349. import types
  350. import traceback
  351. import gc
  352.  
  353. class CalledProcessError(Exception):
  354.     '''This exception is raised when a process run by check_call() returns
  355.     a non-zero exit status.  The exit status will be stored in the
  356.     returncode attribute.'''
  357.     
  358.     def __init__(self, returncode, cmd):
  359.         self.returncode = returncode
  360.         self.cmd = cmd
  361.  
  362.     
  363.     def __str__(self):
  364.         return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
  365.  
  366.  
  367. if mswindows:
  368.     import threading
  369.     import msvcrt
  370.     from _subprocess import *
  371.     
  372.     class STARTUPINFO:
  373.         dwFlags = 0
  374.         hStdInput = None
  375.         hStdOutput = None
  376.         hStdError = None
  377.         wShowWindow = 0
  378.  
  379.     
  380.     class pywintypes:
  381.         error = IOError
  382.  
  383. else:
  384.     import select
  385.     import errno
  386.     import fcntl
  387.     import pickle
  388. __all__ = [
  389.     'Popen',
  390.     'PIPE',
  391.     'STDOUT',
  392.     'call',
  393.     'check_call',
  394.     'CalledProcessError']
  395.  
  396. try:
  397.     MAXFD = os.sysconf('SC_OPEN_MAX')
  398. except:
  399.     MAXFD = 256
  400.  
  401.  
  402. try:
  403.     False
  404. except NameError:
  405.     False = 0
  406.     True = 1
  407.  
  408. _active = []
  409.  
  410. def _cleanup():
  411.     for inst in _active[:]:
  412.         if inst._internal_poll(_deadstate = sys.maxint) >= 0:
  413.             
  414.             try:
  415.                 _active.remove(inst)
  416.             except ValueError:
  417.                 pass
  418.             except:
  419.                 None<EXCEPTION MATCH>ValueError
  420.             
  421.  
  422.         None<EXCEPTION MATCH>ValueError
  423.     
  424.  
  425. PIPE = -1
  426. STDOUT = -2
  427.  
  428. def call(*popenargs, **kwargs):
  429.     '''Run command with arguments.  Wait for command to complete, then
  430.     return the returncode attribute.
  431.  
  432.     The arguments are the same as for the Popen constructor.  Example:
  433.  
  434.     retcode = call(["ls", "-l"])
  435.     '''
  436.     return Popen(*popenargs, **kwargs).wait()
  437.  
  438.  
  439. def check_call(*popenargs, **kwargs):
  440.     '''Run command with arguments.  Wait for command to complete.  If
  441.     the exit code was zero then return, otherwise raise
  442.     CalledProcessError.  The CalledProcessError object will have the
  443.     return code in the returncode attribute.
  444.  
  445.     The arguments are the same as for the Popen constructor.  Example:
  446.  
  447.     check_call(["ls", "-l"])
  448.     '''
  449.     retcode = call(*popenargs, **kwargs)
  450.     cmd = kwargs.get('args')
  451.     if cmd is None:
  452.         cmd = popenargs[0]
  453.     
  454.     if retcode:
  455.         raise CalledProcessError(retcode, cmd)
  456.     
  457.     return retcode
  458.  
  459.  
  460. def list2cmdline(seq):
  461.     '''
  462.     Translate a sequence of arguments into a command line
  463.     string, using the same rules as the MS C runtime:
  464.  
  465.     1) Arguments are delimited by white space, which is either a
  466.        space or a tab.
  467.  
  468.     2) A string surrounded by double quotation marks is
  469.        interpreted as a single argument, regardless of white space
  470.        contained within.  A quoted string can be embedded in an
  471.        argument.
  472.  
  473.     3) A double quotation mark preceded by a backslash is
  474.        interpreted as a literal double quotation mark.
  475.  
  476.     4) Backslashes are interpreted literally, unless they
  477.        immediately precede a double quotation mark.
  478.  
  479.     5) If backslashes immediately precede a double quotation mark,
  480.        every pair of backslashes is interpreted as a literal
  481.        backslash.  If the number of backslashes is odd, the last
  482.        backslash escapes the next double quotation mark as
  483.        described in rule 3.
  484.     '''
  485.     result = []
  486.     needquote = False
  487.     for arg in seq:
  488.         bs_buf = []
  489.         if result:
  490.             result.append(' ')
  491.         
  492.         if not ' ' in arg and '\t' in arg:
  493.             pass
  494.         needquote = arg == ''
  495.         if needquote:
  496.             result.append('"')
  497.         
  498.         for c in arg:
  499.             if c == '\\':
  500.                 bs_buf.append(c)
  501.                 continue
  502.             if c == '"':
  503.                 result.append('\\' * len(bs_buf) * 2)
  504.                 bs_buf = []
  505.                 result.append('\\"')
  506.                 continue
  507.             if bs_buf:
  508.                 result.extend(bs_buf)
  509.                 bs_buf = []
  510.             
  511.             result.append(c)
  512.         
  513.         if bs_buf:
  514.             result.extend(bs_buf)
  515.         
  516.         if needquote:
  517.             result.extend(bs_buf)
  518.             result.append('"')
  519.             continue
  520.     
  521.     return ''.join(result)
  522.  
  523.  
  524. class Popen(object):
  525.     
  526.     def __init__(self, args, bufsize = 0, executable = None, stdin = None, stdout = None, stderr = None, preexec_fn = None, close_fds = False, shell = False, cwd = None, env = None, universal_newlines = False, startupinfo = None, creationflags = 0):
  527.         '''Create new Popen instance.'''
  528.         _cleanup()
  529.         self._child_created = False
  530.         if not isinstance(bufsize, (int, long)):
  531.             raise TypeError('bufsize must be an integer')
  532.         
  533.         if mswindows:
  534.             if preexec_fn is not None:
  535.                 raise ValueError('preexec_fn is not supported on Windows platforms')
  536.             
  537.             if close_fds:
  538.                 raise ValueError('close_fds is not supported on Windows platforms')
  539.             
  540.         elif startupinfo is not None:
  541.             raise ValueError('startupinfo is only supported on Windows platforms')
  542.         
  543.         if creationflags != 0:
  544.             raise ValueError('creationflags is only supported on Windows platforms')
  545.         
  546.         self.stdin = None
  547.         self.stdout = None
  548.         self.stderr = None
  549.         self.pid = None
  550.         self.returncode = None
  551.         self.universal_newlines = universal_newlines
  552.         (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  553.         self._execute_child(args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  554.         if mswindows:
  555.             if stdin is None and p2cwrite is not None:
  556.                 os.close(p2cwrite)
  557.                 p2cwrite = None
  558.             
  559.             if stdout is None and c2pread is not None:
  560.                 os.close(c2pread)
  561.                 c2pread = None
  562.             
  563.             if stderr is None and errread is not None:
  564.                 os.close(errread)
  565.                 errread = None
  566.             
  567.         
  568.         if p2cwrite:
  569.             self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
  570.         
  571.         if c2pread:
  572.             if universal_newlines:
  573.                 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
  574.             else:
  575.                 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
  576.         
  577.         if errread:
  578.             if universal_newlines:
  579.                 self.stderr = os.fdopen(errread, 'rU', bufsize)
  580.             else:
  581.                 self.stderr = os.fdopen(errread, 'rb', bufsize)
  582.         
  583.  
  584.     
  585.     def _translate_newlines(self, data):
  586.         data = data.replace('\r\n', '\n')
  587.         data = data.replace('\r', '\n')
  588.         return data
  589.  
  590.     
  591.     def __del__(self, sys = sys):
  592.         if not self._child_created:
  593.             return None
  594.         
  595.         self._internal_poll(_deadstate = sys.maxint)
  596.         if self.returncode is None and _active is not None:
  597.             _active.append(self)
  598.         
  599.  
  600.     
  601.     def communicate(self, input = None):
  602.         '''Interact with process: Send data to stdin.  Read data from
  603.         stdout and stderr, until end-of-file is reached.  Wait for
  604.         process to terminate.  The optional input argument should be a
  605.         string to be sent to the child process, or None, if no data
  606.         should be sent to the child.
  607.  
  608.         communicate() returns a tuple (stdout, stderr).'''
  609.         if [
  610.             self.stdin,
  611.             self.stdout,
  612.             self.stderr].count(None) >= 2:
  613.             stdout = None
  614.             stderr = None
  615.             if self.stdin:
  616.                 if input:
  617.                     self._fo_write_no_intr(self.stdin, input)
  618.                 
  619.                 self.stdin.close()
  620.             elif self.stdout:
  621.                 stdout = self._fo_read_no_intr(self.stdout)
  622.                 self.stdout.close()
  623.             elif self.stderr:
  624.                 stderr = self._fo_read_no_intr(self.stderr)
  625.                 self.stderr.close()
  626.             
  627.             self.wait()
  628.             return (stdout, stderr)
  629.         
  630.         return self._communicate(input)
  631.  
  632.     
  633.     def poll(self):
  634.         return self._internal_poll()
  635.  
  636.     if mswindows:
  637.         
  638.         def _get_handles(self, stdin, stdout, stderr):
  639.             '''Construct and return tupel with IO objects:
  640.             p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  641.             '''
  642.             if stdin is None and stdout is None and stderr is None:
  643.                 return (None, None, None, None, None, None)
  644.             
  645.             (p2cread, p2cwrite) = (None, None)
  646.             (c2pread, c2pwrite) = (None, None)
  647.             (errread, errwrite) = (None, None)
  648.             if stdin is None:
  649.                 p2cread = GetStdHandle(STD_INPUT_HANDLE)
  650.             
  651.             if p2cread is not None:
  652.                 pass
  653.             elif stdin is None or stdin == PIPE:
  654.                 (p2cread, p2cwrite) = CreatePipe(None, 0)
  655.                 p2cwrite = p2cwrite.Detach()
  656.                 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
  657.             elif isinstance(stdin, int):
  658.                 p2cread = msvcrt.get_osfhandle(stdin)
  659.             else:
  660.                 p2cread = msvcrt.get_osfhandle(stdin.fileno())
  661.             p2cread = self._make_inheritable(p2cread)
  662.             if stdout is None:
  663.                 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
  664.             
  665.             if c2pwrite is not None:
  666.                 pass
  667.             elif stdout is None or stdout == PIPE:
  668.                 (c2pread, c2pwrite) = CreatePipe(None, 0)
  669.                 c2pread = c2pread.Detach()
  670.                 c2pread = msvcrt.open_osfhandle(c2pread, 0)
  671.             elif isinstance(stdout, int):
  672.                 c2pwrite = msvcrt.get_osfhandle(stdout)
  673.             else:
  674.                 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
  675.             c2pwrite = self._make_inheritable(c2pwrite)
  676.             if stderr is None:
  677.                 errwrite = GetStdHandle(STD_ERROR_HANDLE)
  678.             
  679.             if errwrite is not None:
  680.                 pass
  681.             elif stderr is None or stderr == PIPE:
  682.                 (errread, errwrite) = CreatePipe(None, 0)
  683.                 errread = errread.Detach()
  684.                 errread = msvcrt.open_osfhandle(errread, 0)
  685.             elif stderr == STDOUT:
  686.                 errwrite = c2pwrite
  687.             elif isinstance(stderr, int):
  688.                 errwrite = msvcrt.get_osfhandle(stderr)
  689.             else:
  690.                 errwrite = msvcrt.get_osfhandle(stderr.fileno())
  691.             errwrite = self._make_inheritable(errwrite)
  692.             return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  693.  
  694.         
  695.         def _make_inheritable(self, handle):
  696.             '''Return a duplicate of handle, which is inheritable'''
  697.             return DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), 0, 1, DUPLICATE_SAME_ACCESS)
  698.  
  699.         
  700.         def _find_w9xpopen(self):
  701.             '''Find and return absolut path to w9xpopen.exe'''
  702.             w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), 'w9xpopen.exe')
  703.             if not os.path.exists(w9xpopen):
  704.                 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), 'w9xpopen.exe')
  705.                 if not os.path.exists(w9xpopen):
  706.                     raise RuntimeError('Cannot locate w9xpopen.exe, which is needed for Popen to work with your shell or platform.')
  707.                 
  708.             
  709.             return w9xpopen
  710.  
  711.         
  712.         def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite):
  713.             '''Execute program (MS Windows version)'''
  714.             if not isinstance(args, types.StringTypes):
  715.                 args = list2cmdline(args)
  716.             
  717.             if startupinfo is None:
  718.                 startupinfo = STARTUPINFO()
  719.             
  720.             if None not in (p2cread, c2pwrite, errwrite):
  721.                 startupinfo.dwFlags |= STARTF_USESTDHANDLES
  722.                 startupinfo.hStdInput = p2cread
  723.                 startupinfo.hStdOutput = c2pwrite
  724.                 startupinfo.hStdError = errwrite
  725.             
  726.             if shell:
  727.                 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
  728.                 startupinfo.wShowWindow = SW_HIDE
  729.                 comspec = os.environ.get('COMSPEC', 'cmd.exe')
  730.                 args = comspec + ' /c ' + args
  731.                 if GetVersion() >= 0x80000000L or os.path.basename(comspec).lower() == 'command.com':
  732.                     w9xpopen = self._find_w9xpopen()
  733.                     args = '"%s" %s' % (w9xpopen, args)
  734.                     creationflags |= CREATE_NEW_CONSOLE
  735.                 
  736.             
  737.             
  738.             try:
  739.                 (hp, ht, pid, tid) = CreateProcess(executable, args, None, None, 1, creationflags, env, cwd, startupinfo)
  740.             except pywintypes.error:
  741.                 e = None
  742.                 raise WindowsError(*e.args)
  743.  
  744.             self._child_created = True
  745.             self._handle = hp
  746.             self.pid = pid
  747.             ht.Close()
  748.             if p2cread is not None:
  749.                 p2cread.Close()
  750.             
  751.             if c2pwrite is not None:
  752.                 c2pwrite.Close()
  753.             
  754.             if errwrite is not None:
  755.                 errwrite.Close()
  756.             
  757.  
  758.         
  759.         def _internal_poll(self, _deadstate = None):
  760.             '''Check if child process has terminated.  Returns returncode
  761.             attribute.'''
  762.             if self.returncode is None:
  763.                 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
  764.                     self.returncode = GetExitCodeProcess(self._handle)
  765.                 
  766.             
  767.             return self.returncode
  768.  
  769.         
  770.         def wait(self):
  771.             '''Wait for child process to terminate.  Returns returncode
  772.             attribute.'''
  773.             if self.returncode is None:
  774.                 obj = WaitForSingleObject(self._handle, INFINITE)
  775.                 self.returncode = GetExitCodeProcess(self._handle)
  776.             
  777.             return self.returncode
  778.  
  779.         
  780.         def _readerthread(self, fh, buffer):
  781.             buffer.append(fh.read())
  782.  
  783.         
  784.         def _communicate(self, input):
  785.             stdout = None
  786.             stderr = None
  787.             if self.stdout:
  788.                 stdout = []
  789.                 stdout_thread = threading.Thread(target = self._readerthread, args = (self.stdout, stdout))
  790.                 stdout_thread.setDaemon(True)
  791.                 stdout_thread.start()
  792.             
  793.             if self.stderr:
  794.                 stderr = []
  795.                 stderr_thread = threading.Thread(target = self._readerthread, args = (self.stderr, stderr))
  796.                 stderr_thread.setDaemon(True)
  797.                 stderr_thread.start()
  798.             
  799.             if self.stdin:
  800.                 if input is not None:
  801.                     self.stdin.write(input)
  802.                 
  803.                 self.stdin.close()
  804.             
  805.             if self.stdout:
  806.                 stdout_thread.join()
  807.             
  808.             if self.stderr:
  809.                 stderr_thread.join()
  810.             
  811.             if stdout is not None:
  812.                 stdout = stdout[0]
  813.             
  814.             if stderr is not None:
  815.                 stderr = stderr[0]
  816.             
  817.             if self.universal_newlines and hasattr(file, 'newlines'):
  818.                 if stdout:
  819.                     stdout = self._translate_newlines(stdout)
  820.                 
  821.                 if stderr:
  822.                     stderr = self._translate_newlines(stderr)
  823.                 
  824.             
  825.             self.wait()
  826.             return (stdout, stderr)
  827.  
  828.     else:
  829.         
  830.         def _get_handles(self, stdin, stdout, stderr):
  831.             '''Construct and return tupel with IO objects:
  832.             p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  833.             '''
  834.             (p2cread, p2cwrite) = (None, None)
  835.             (c2pread, c2pwrite) = (None, None)
  836.             (errread, errwrite) = (None, None)
  837.             if stdin is None:
  838.                 pass
  839.             elif stdin == PIPE:
  840.                 (p2cread, p2cwrite) = os.pipe()
  841.             elif isinstance(stdin, int):
  842.                 p2cread = stdin
  843.             else:
  844.                 p2cread = stdin.fileno()
  845.             if stdout is None:
  846.                 pass
  847.             elif stdout == PIPE:
  848.                 (c2pread, c2pwrite) = os.pipe()
  849.             elif isinstance(stdout, int):
  850.                 c2pwrite = stdout
  851.             else:
  852.                 c2pwrite = stdout.fileno()
  853.             if stderr is None:
  854.                 pass
  855.             elif stderr == PIPE:
  856.                 (errread, errwrite) = os.pipe()
  857.             elif stderr == STDOUT:
  858.                 errwrite = c2pwrite
  859.             elif isinstance(stderr, int):
  860.                 errwrite = stderr
  861.             else:
  862.                 errwrite = stderr.fileno()
  863.             return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  864.  
  865.         
  866.         def _set_cloexec_flag(self, fd):
  867.             
  868.             try:
  869.                 cloexec_flag = fcntl.FD_CLOEXEC
  870.             except AttributeError:
  871.                 cloexec_flag = 1
  872.  
  873.             old = fcntl.fcntl(fd, fcntl.F_GETFD)
  874.             fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
  875.  
  876.         
  877.         def _close_fds(self, but):
  878.             for i in xrange(3, MAXFD):
  879.                 if i == but:
  880.                     continue
  881.                 
  882.                 
  883.                 try:
  884.                     os.close(i)
  885.                 continue
  886.                 continue
  887.  
  888.             
  889.  
  890.         
  891.         def _read_no_intr(self, fd, buffersize):
  892.             '''Like os.read, but retries on EINTR'''
  893.             while True:
  894.                 
  895.                 try:
  896.                     return os.read(fd, buffersize)
  897.                 continue
  898.                 except OSError:
  899.                     e = None
  900.                     if e.errno == errno.EINTR:
  901.                         continue
  902.                     else:
  903.                         raise 
  904.                     e.errno == errno.EINTR
  905.                 
  906.  
  907.                 None<EXCEPTION MATCH>OSError
  908.  
  909.         
  910.         def _write_no_intr(self, fd, s):
  911.             '''Like os.write, but retries on EINTR'''
  912.             while True:
  913.                 
  914.                 try:
  915.                     return os.write(fd, s)
  916.                 continue
  917.                 except OSError:
  918.                     e = None
  919.                     if e.errno == errno.EINTR:
  920.                         continue
  921.                     else:
  922.                         raise 
  923.                     e.errno == errno.EINTR
  924.                 
  925.  
  926.                 None<EXCEPTION MATCH>OSError
  927.  
  928.         
  929.         def _waitpid_no_intr(self, pid, options):
  930.             '''Like os.waitpid, but retries on EINTR'''
  931.             while True:
  932.                 
  933.                 try:
  934.                     return os.waitpid(pid, options)
  935.                 continue
  936.                 except OSError:
  937.                     e = None
  938.                     if e.errno == errno.EINTR:
  939.                         continue
  940.                     else:
  941.                         raise 
  942.                     e.errno == errno.EINTR
  943.                 
  944.  
  945.                 None<EXCEPTION MATCH>OSError
  946.  
  947.         
  948.         def _fo_read_no_intr(self, obj):
  949.             '''Like obj.read(), but retries on EINTR'''
  950.             while True:
  951.                 
  952.                 try:
  953.                     return obj.read()
  954.                 continue
  955.                 except IOError:
  956.                     e = None
  957.                     if e.errno == errno.EINTR:
  958.                         continue
  959.                     else:
  960.                         raise 
  961.                     e.errno == errno.EINTR
  962.                 
  963.  
  964.                 None<EXCEPTION MATCH>IOError
  965.  
  966.         
  967.         def _fo_write_no_intr(self, obj, data):
  968.             '''Like obj.write(), but retries on EINTR'''
  969.             while True:
  970.                 
  971.                 try:
  972.                     return obj.write(data)
  973.                 continue
  974.                 except IOError:
  975.                     e = None
  976.                     if e.errno == errno.EINTR:
  977.                         continue
  978.                     else:
  979.                         raise 
  980.                     e.errno == errno.EINTR
  981.                 
  982.  
  983.                 None<EXCEPTION MATCH>IOError
  984.  
  985.         
  986.         def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite):
  987.             '''Execute program (POSIX version)'''
  988.             if isinstance(args, types.StringTypes):
  989.                 args = [
  990.                     args]
  991.             else:
  992.                 args = list(args)
  993.             if shell:
  994.                 args = [
  995.                     '/bin/sh',
  996.                     '-c'] + args
  997.             
  998.             if executable is None:
  999.                 executable = args[0]
  1000.             
  1001.             (errpipe_read, errpipe_write) = os.pipe()
  1002.             self._set_cloexec_flag(errpipe_write)
  1003.             gc_was_enabled = gc.isenabled()
  1004.             gc.disable()
  1005.             
  1006.             try:
  1007.                 self.pid = os.fork()
  1008.             except:
  1009.                 if gc_was_enabled:
  1010.                     gc.enable()
  1011.                 
  1012.                 raise 
  1013.  
  1014.             self._child_created = True
  1015.             if self.pid == 0:
  1016.                 
  1017.                 try:
  1018.                     if p2cwrite:
  1019.                         os.close(p2cwrite)
  1020.                     
  1021.                     if c2pread:
  1022.                         os.close(c2pread)
  1023.                     
  1024.                     if errread:
  1025.                         os.close(errread)
  1026.                     
  1027.                     os.close(errpipe_read)
  1028.                     if p2cread:
  1029.                         os.dup2(p2cread, 0)
  1030.                     
  1031.                     if c2pwrite:
  1032.                         os.dup2(c2pwrite, 1)
  1033.                     
  1034.                     if errwrite:
  1035.                         os.dup2(errwrite, 2)
  1036.                     
  1037.                     if p2cread and p2cread not in (0,):
  1038.                         os.close(p2cread)
  1039.                     
  1040.                     if c2pwrite and c2pwrite not in (p2cread, 1):
  1041.                         os.close(c2pwrite)
  1042.                     
  1043.                     if errwrite and errwrite not in (p2cread, c2pwrite, 2):
  1044.                         os.close(errwrite)
  1045.                     
  1046.                     if close_fds:
  1047.                         self._close_fds(but = errpipe_write)
  1048.                     
  1049.                     if cwd is not None:
  1050.                         os.chdir(cwd)
  1051.                     
  1052.                     if preexec_fn:
  1053.                         apply(preexec_fn)
  1054.                     
  1055.                     if env is None:
  1056.                         os.execvp(executable, args)
  1057.                     else:
  1058.                         os.execvpe(executable, args, env)
  1059.                 except:
  1060.                     (exc_type, exc_value, tb) = sys.exc_info()
  1061.                     exc_lines = traceback.format_exception(exc_type, exc_value, tb)
  1062.                     exc_value.child_traceback = ''.join(exc_lines)
  1063.                     self._write_no_intr(errpipe_write, pickle.dumps(exc_value))
  1064.  
  1065.                 os._exit(255)
  1066.             
  1067.             if gc_was_enabled:
  1068.                 gc.enable()
  1069.             
  1070.             os.close(errpipe_write)
  1071.             if p2cread and p2cwrite:
  1072.                 os.close(p2cread)
  1073.             
  1074.             if c2pwrite and c2pread:
  1075.                 os.close(c2pwrite)
  1076.             
  1077.             if errwrite and errread:
  1078.                 os.close(errwrite)
  1079.             
  1080.             data = self._read_no_intr(errpipe_read, 1048576)
  1081.             os.close(errpipe_read)
  1082.             if data != '':
  1083.                 self._waitpid_no_intr(self.pid, 0)
  1084.                 child_exception = pickle.loads(data)
  1085.                 raise child_exception
  1086.             
  1087.  
  1088.         
  1089.         def _handle_exitstatus(self, sts):
  1090.             if os.WIFSIGNALED(sts):
  1091.                 self.returncode = -os.WTERMSIG(sts)
  1092.             elif os.WIFEXITED(sts):
  1093.                 self.returncode = os.WEXITSTATUS(sts)
  1094.             else:
  1095.                 raise RuntimeError('Unknown child exit status!')
  1096.  
  1097.         
  1098.         def _internal_poll(self, _deadstate = None):
  1099.             '''Check if child process has terminated.  Returns returncode
  1100.             attribute.'''
  1101.             if self.returncode is None:
  1102.                 
  1103.                 try:
  1104.                     (pid, sts) = self._waitpid_no_intr(self.pid, os.WNOHANG)
  1105.                     if pid == self.pid:
  1106.                         self._handle_exitstatus(sts)
  1107.                 except os.error:
  1108.                     if _deadstate is not None:
  1109.                         self.returncode = _deadstate
  1110.                     
  1111.                 except:
  1112.                     _deadstate is not None
  1113.                 
  1114.  
  1115.             None<EXCEPTION MATCH>os.error
  1116.             return self.returncode
  1117.  
  1118.         
  1119.         def wait(self):
  1120.             '''Wait for child process to terminate.  Returns returncode
  1121.             attribute.'''
  1122.             if self.returncode is None:
  1123.                 (pid, sts) = self._waitpid_no_intr(self.pid, 0)
  1124.                 self._handle_exitstatus(sts)
  1125.             
  1126.             return self.returncode
  1127.  
  1128.         
  1129.         def _communicate(self, input):
  1130.             read_set = []
  1131.             write_set = []
  1132.             stdout = None
  1133.             stderr = None
  1134.             if self.stdin:
  1135.                 self.stdin.flush()
  1136.                 if input:
  1137.                     write_set.append(self.stdin)
  1138.                 else:
  1139.                     self.stdin.close()
  1140.             
  1141.             if self.stdout:
  1142.                 read_set.append(self.stdout)
  1143.                 stdout = []
  1144.             
  1145.             if self.stderr:
  1146.                 read_set.append(self.stderr)
  1147.                 stderr = []
  1148.             
  1149.             input_offset = 0
  1150.             while read_set or write_set:
  1151.                 
  1152.                 try:
  1153.                     (rlist, wlist, xlist) = select.select(read_set, write_set, [])
  1154.                 except select.error:
  1155.                     e = None
  1156.                     if e.args[0] == errno.EINTR:
  1157.                         continue
  1158.                     
  1159.                     raise 
  1160.  
  1161.                 if self.stdin in wlist:
  1162.                     bytes_written = self._write_no_intr(self.stdin.fileno(), buffer(input, input_offset, 512))
  1163.                     input_offset += bytes_written
  1164.                     if input_offset >= len(input):
  1165.                         self.stdin.close()
  1166.                         write_set.remove(self.stdin)
  1167.                     
  1168.                 
  1169.                 if self.stdout in rlist:
  1170.                     data = self._read_no_intr(self.stdout.fileno(), 1024)
  1171.                     if data == '':
  1172.                         self.stdout.close()
  1173.                         read_set.remove(self.stdout)
  1174.                     
  1175.                     stdout.append(data)
  1176.                 
  1177.                 if self.stderr in rlist:
  1178.                     data = self._read_no_intr(self.stderr.fileno(), 1024)
  1179.                     if data == '':
  1180.                         self.stderr.close()
  1181.                         read_set.remove(self.stderr)
  1182.                     
  1183.                     stderr.append(data)
  1184.                     continue
  1185.             if stdout is not None:
  1186.                 stdout = ''.join(stdout)
  1187.             
  1188.             if stderr is not None:
  1189.                 stderr = ''.join(stderr)
  1190.             
  1191.             if self.universal_newlines and hasattr(file, 'newlines'):
  1192.                 if stdout:
  1193.                     stdout = self._translate_newlines(stdout)
  1194.                 
  1195.                 if stderr:
  1196.                     stderr = self._translate_newlines(stderr)
  1197.                 
  1198.             
  1199.             self.wait()
  1200.             return (stdout, stderr)
  1201.  
  1202.  
  1203.  
  1204. def _demo_posix():
  1205.     plist = Popen([
  1206.         'ps'], stdout = PIPE).communicate()[0]
  1207.     print 'Process list:'
  1208.     print plist
  1209.     if os.getuid() == 0:
  1210.         p = Popen([
  1211.             'id'], preexec_fn = (lambda : os.setuid(100)))
  1212.         p.wait()
  1213.     
  1214.     print "Looking for 'hda'..."
  1215.     p1 = Popen([
  1216.         'dmesg'], stdout = PIPE)
  1217.     p2 = Popen([
  1218.         'grep',
  1219.         'hda'], stdin = p1.stdout, stdout = PIPE)
  1220.     print repr(p2.communicate()[0])
  1221.     print 
  1222.     print 'Trying a weird file...'
  1223.     
  1224.     try:
  1225.         print Popen([
  1226.             '/this/path/does/not/exist']).communicate()
  1227.     except OSError:
  1228.         e = None
  1229.         if e.errno == errno.ENOENT:
  1230.             print "The file didn't exist.  I thought so..."
  1231.             print 'Child traceback:'
  1232.             print e.child_traceback
  1233.         else:
  1234.             print 'Error', e.errno
  1235.     except:
  1236.         e.errno == errno.ENOENT
  1237.  
  1238.     print >>sys.stderr, 'Gosh.  No error.'
  1239.  
  1240.  
  1241. def _demo_windows():
  1242.     print "Looking for 'PROMPT' in set output..."
  1243.     p1 = Popen('set', stdout = PIPE, shell = True)
  1244.     p2 = Popen('find "PROMPT"', stdin = p1.stdout, stdout = PIPE)
  1245.     print repr(p2.communicate()[0])
  1246.     print 'Executing calc...'
  1247.     p = Popen('calc')
  1248.     p.wait()
  1249.  
  1250. if __name__ == '__main__':
  1251.     if mswindows:
  1252.         _demo_windows()
  1253.     else:
  1254.         _demo_posix()
  1255.  
  1256.